package com.falling.reggie.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.falling.reggie.common.CustomException;
import com.falling.reggie.dto.SetmealDto;
import com.falling.reggie.entity.SetMeal;
import com.falling.reggie.entity.SetmealDish;
import com.falling.reggie.mapper.SetMealMapper;
import com.falling.reggie.service.SetMealService;
import com.falling.reggie.service.SetmealDishService;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.stream.Collectors;

@Service
public class SetMealServiceImpl extends ServiceImpl<SetMealMapper, SetMeal>
        implements SetMealService {

    @Resource
    private SetmealDishService setmealDishService;

    @Override
    @Transactional
    public boolean saveWithDish(SetmealDto setmealDto) {
        // 保存setmeal基本信息
        super.save(setmealDto);

        // 保存setmeal_dish关系信息
        List<SetmealDish> setmealDishes = setmealDto.getSetmealDishes();
        List<SetmealDish> setmealDishList = setmealDishes.stream().peek((item) ->
                item.setSetmealId(setmealDto.getId())
        ).collect(Collectors.toList());

        return setmealDishService.saveBatch(setmealDishList);
    }

    @Override
    @Transactional
    public boolean removeWithDish(List<Long> ids) {
        // 判断是否正在售出，是则抛出业务异常
        LambdaQueryWrapper<SetMeal> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.in(SetMeal::getId, ids);
        queryWrapper.eq(SetMeal::getStatus, 1); // 正在售卖

        int count = this.count(queryWrapper);
        if (count > 0) throw new CustomException("this set meal is selling");

        // 删除setmeal表中数据
        super.removeByIds(ids);

        // 删除setmeal_dish表中数据
        LambdaQueryWrapper<SetmealDish> setmealDishQueryWrapper = new LambdaQueryWrapper<>();
        setmealDishQueryWrapper.in(SetmealDish::getSetmealId, ids);

        return setmealDishService.remove(setmealDishQueryWrapper);
    }

    @Override
    public SetmealDto getByIdWithDish(Long id) {
        SetmealDto setmealDto = new SetmealDto();
        SetMeal setMeal = super.getById(id);
        LambdaQueryWrapper<SetmealDish> queryWrapper = new LambdaQueryWrapper<>();
        queryWrapper.eq(SetmealDish::getSetmealId, setMeal.getId());
        List<SetmealDish> dishes = setmealDishService.list(queryWrapper);

        BeanUtils.copyProperties(setMeal, setmealDto);
        setmealDto.setSetmealDishes(dishes);

        return setmealDto;
    }
}
